package com.pashanhoo.netty.simple;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @author 胡庆安
 * @version V1.0
 * @Package com.pashanhoo.netty.simple
 * @date 2020/11/6 8:54
 * @Copyright © 2010-2020 爬山虎科技（扬州）股份有限公司
 */
public class NettyServer {
    public static void main(String[] args) throws Exception{
        //创建两个线程组
        //bossGroup只处理连接请求
        //workerGroup只处理业务请求
        //两个都是无限循环
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {

            //创建服务器端启动的对象，配置参数
            ServerBootstrap bootstrap = new ServerBootstrap();

            //链式编程
            bootstrap.group(bossGroup,workerGroup)//设置连个线程组
                    .channel(NioServerSocketChannel.class)//设置服务器的通道实现
                    .option(ChannelOption.SO_BACKLOG,128)//设置线程队列等待的数目
                    .childOption(ChannelOption.SO_KEEPALIVE,true)//设置保持活动连接状态
                    .childHandler(new ChannelInitializer<SocketChannel>() {//创建一个通道测试对象
                        //给pipeline设置处理器
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new NettyServerHandler());
                        }
                    });//给我们的workerGroup的Eventloopd对应的管道

            System.out.println("...服务器 is ready ....");

            //绑定一个端口并同步
            ChannelFuture cf = bootstrap.bind(6668).sync();

            //对关闭通道进行监听
            cf.channel().closeFuture().sync();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }
}
